package drp.snowbell.module;

import java.util.ArrayList;
import java.util.Collection;

import drp.snowbell.cache.CacheSystem;
import drp.snowbell.cache.ICache;
import drp.snowbell.cfg.EntityConfig;
import drp.snowbell.cfg.ModuleConfig;
import drp.snowbell.cfg.PartConfig;
import drp.snowbell.cfg.init.ModuleLoader;
import drp.snowbell.exception.CatchException;


/**
 * 模块管理器
 * 
 * @author wuhj
 * 
 */
public class ModuleManager {

	private static ICache<String, IModule> moduleCache = CacheSystem.getCache(ModuleManager.class.getName() + "#moduleCache");

	/**
	 * 注册一个模块
	 * 
	 * @param config
	 */
	public static synchronized boolean register(ModuleConfig config) {
		boolean ret = false;
		ModuleLoader loader = ModuleLoader.getInstance();
		Collection<EntityConfig> entityList = new ArrayList<EntityConfig>();
		Collection<PartConfig> partList = new ArrayList<PartConfig>();
		loader.loadModule(config.getName(), entityList, partList);
		Class<? extends IModule> moduleClass = loader.getModuleClass(config.getName());
		IModule mod = null;
		if (moduleClass == null) {
			mod = new DefaultModule();
		} else {
			try {
				mod = moduleClass.newInstance();
			} catch (Exception e) {
				CatchException.take(ModuleManager.class, e);
			}
		}
		if (mod != null) {
			mod.initialize(config, entityList, partList);// 初始化
			moduleCache.put(config.getName(), mod);
			ret = true;
		}
		return ret;
	}

	public static IModule getModule(String moduleName) {
		return moduleCache.get(moduleName);
	}
}
